package server;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Server {
	private final String verision = "1";

	// private final int CLIENT_CONNECT = 1;  (unused)
	private final int CLIENT_DISCONNECT = 2;
	private final int CLIENT_SETNAME = 3;
	private final int CLIENT_POS = 4; // (will be used later)

	private final String DEFAULT_REGEX = "|";

	private boolean run = true;
	private ServerSocket server;
	private ArrayList<Client> clients = new ArrayList<Client>();

	private int width = 800, height = 600;
	private JFrame frame = new JFrame("Server");
	private JTextArea text = new JTextArea();
	private JTextField input = new JTextField();
	
	public Server() {
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setResizable(false);
		frame.setLayout(new BorderLayout());
		frame.setSize(width, height);
		text.setEnabled(false);
		frame.add(text, BorderLayout.CENTER);
		frame.add(input, BorderLayout.SOUTH);
		frame.setLocationRelativeTo(null);
	}
	
	public void start(int port) {
		frame.setVisible(true);
		run = true;
		try {
			server = new ServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
		}
		listen();
	}

	private void listen() {
		new Thread("Listen") {
			public void run() {
				while (isRunning()) {
					try {
						Socket s = server.accept();
						addClient(s);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
	}

	public void stop() {
		for (int i = 0; i < clients.size(); i++) {
			clients.get(i).disconnect();
		}
		try {
			server.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		run = false;
	}

	private void addClient(Socket s) {
		clients.add(new Client(this, s));
	}

	public void send() {
		
	}

	public boolean isRunning() {
		return run;
	}

	public void process(Client c, String s) {
		String data[] = s.split(DEFAULT_REGEX);
		int id = -1;
		try {
			id = Integer.parseInt(data[0]);
		} catch (Exception e) {
			System.err.println("Invalid packet id: " + id);
			return;
		}

		switch (id) {
		case CLIENT_SETNAME:
			c.setName(data[1]);
			break;
		case CLIENT_DISCONNECT:
			c.disconnect();
			break;
		}
	}
}
